<?php
/**
 * The control file of report module of ZenTaoPMS.
 *
 * @copyright   Copyright 2009-2015 青岛易软天创网络科技有限公司(QingDao Nature Easy Soft Network Technology Co,LTD, www.cnezsoft.com)
 * @license     ZPL (http://zpl.pub/page/zplv12.html)
 * @author      Chunsheng Wang <chunsheng@cnezsoft.com>
 * @package     report
 * @version     $Id: control.php 4622 2013-03-28 01:09:02Z chencongzhi520@gmail.com $
 * @link        http://www.zentao.net
 */
class report extends control
{
    /**
     * The index of report, goto project deviation.
     * 
     * @access public
     * @return void
     */
    public function index()
    {
        $this->locate(inlink('productSummary')); 
    }
    
    /**
     * Project deviation report.
     * 
     * @access public
     * @return void
     */
    public function projectDeviation($begin = 0, $end = 0)
    {
        $begin = $begin ? date('Y-m-d', strtotime($begin)) : '';
        $end   = $end   ? date('Y-m-d', strtotime($end))   : '';

        $this->view->title      = $this->lang->report->projectDeviation;
        $this->view->position[] = $this->lang->report->projectDeviation;

        $this->view->projects = $this->report->getProjects($begin, $end);
        $this->view->begin    = $begin;
        $this->view->end      = $end;
        $this->view->submenu  = 'project';
        $this->display();
    }

    /**
     * Product information report.
     * 
     * @access public
     * @return void
     */
    public function productSummary($conditions = '')
    {
        $this->app->loadLang('product');
        $this->app->loadLang('productplan');
        $this->app->loadLang('story');
        $this->view->title      = $this->lang->report->productSummary;
        $this->view->position[] = $this->lang->report->productSummary;
        $this->view->products   = $this->report->getProducts($conditions);
        $this->view->users      = $this->loadModel('user')->getPairs('noletter|noclosed');
        $this->view->submenu    = 'product';
        $this->view->conditions = $conditions;
        $this->display();
    }

    /**
     * Bug create report.
     * 
     * @param  int    $begin 
     * @param  int    $end 
     * @access public
     * @return void
     */
    public function bugCreate($begin = 0, $end = 0, $product = 0, $project = 0)
    {
        $this->app->loadLang('bug');
        $begin = $begin == 0 ? date('Y-m-d', strtotime('last month', strtotime(date('Y-m',time()) . '-01 00:00:01'))) : date('Y-m-d', strtotime($begin));
        $end   = $end == 0   ? date('Y-m-d', strtotime('now')) : $end = date('Y-m-d', strtotime($end));

        $this->view->title      = $this->lang->report->bugCreate;
        $this->view->position[] = $this->lang->report->bugCreate;
        $this->view->begin      = $begin;
        $this->view->end        = $end;
        $this->view->bugs       = $this->report->getBugs($begin, $end, $product, $project);
        $this->view->users      = $this->loadModel('user')->getPairs('noletter|noclosed|nodeleted');
        $this->view->projects   = array('' => '') + $this->loadModel('project')->getPairs();
        $this->view->products   = array('' => '') + $this->loadModel('product')->getPairs();
        $this->view->project    = $project;
        $this->view->product    = $product;
        $this->view->submenu    = 'test';
        $this->display(); 
    }

    /**
     * Bug assign report.
     * 
     * @access public
     * @return void
     */
    public function bugAssign()
    {
        $this->view->title      = $this->lang->report->bugAssign;
        $this->view->position[] = $this->lang->report->bugAssign;
        $this->view->submenu    = 'test';
        $this->view->assigns    = $this->report->getBugAssign();
        $this->view->users      = $this->loadModel('user')->getPairs('noletter|noclosed|nodeleted');
        $this->display(); 
    }


    /**
     * Bug daily report.
     *
     * @access public
     * @return void
     */
    public function bugDaily()
    {

        //$projects = $this->loadModel('project')->getPairs('noclosed');
        $products = $this->loadModel('product')->getPairs('noclosed');
        $assigns    = $this->report->getBugAssign();
        $newAssigns = array();
        foreach($assigns as $key => $value){
            $bugs = $value['bug'];
            $newBugs = array();
            $total = 0;



            foreach($bugs as $k => $v){
                if(in_array($k, $products)){
                    $newBugs[$k] = $v;
                    $total += $v['count'];
                }
            }

            $assigns[$key]['bug'] = $newBugs;
            $assigns[$key]['total']['count'] = $total;
            if($total > 0){
                $newAssigns[$key] = $assigns[$key];
            }
        }



       $this->view->assigns = $newAssigns;
       $this->view->users      =  $this->loadModel('user')->getByDepId(1);
       $this->display();
    }

    /**
     * Task delay daily report.
     *
     * @access public
     * @return void
     */
    public function taskDelayedDaily()
    {
        $projects = $this->loadModel('project')->getPairs('noclosed');
        $assigns    = $this->report->getTaskDelayedAssign();
        $this->view->users      =  $this->loadModel('user')->getByDepId(1);

        $newAssigns = array();
        foreach($assigns as $key => $value){
            $tasks = $value['task'];
            $newTasks = array();
            $total = 0;
            foreach($tasks as $k => $v){
                if(in_array($k, $projects)){
                    $newTasks[$k] = $v;
                    $total += $v['count'];
                }
            }
            $assigns[$key]['task'] = $newTasks;
            $assigns[$key]['total']['count'] = $total;
            if($total > 0){
                $newAssigns[$key] = $assigns[$key];
            }
        }


        $this->view->assigns = $newAssigns;

        $this->display();
    }

    /**
     * Workload report.
     * 
     * @access public
     * @return void
     */
    public function workload($begin = '', $end = '', $days = 0, $workday = 7, $dept = 0)
    {
        if($_POST)
        {
            $data     = fixer::input('post')->get();
            $begin    = $data->begin;
            $end      = $data->end;
            $dept     = $data->dept;
            $days     = $data->days;
            $workday  = $data->workday;
        }

        $begin = $begin ? date('Y-m-d', strtotime($begin)) : date('Y-m-d', strtotime('now'));
        $end   = $end   ? date('Y-m-d', strtotime($end))   : date('Y-m-d', strtotime('+1 week'));

        if(!$days)
        {
            $diffDays = helper::diffDate($end, $begin);
            $days     = round($diffDays - ($diffDays / 7 * 2));
        }

        $this->view->title      = $this->lang->report->workload;
        $this->view->position[] = $this->lang->report->workload;

        $this->view->workload = $this->report->getWorkload($dept);
        $this->view->users    = $this->loadModel('user')->getPairs('noletter|noclosed|nodeleted');
        $this->view->depts    = $this->loadModel('dept')->getOptionMenu();
        $this->view->begin    = $begin;
        $this->view->end      = $end;
        $this->view->days     = $days;
        $this->view->workday  = $workday;
        $this->view->dept     = $dept;
        $this->view->allHour  = $days * $workday;
        $this->view->submenu  = 'staff';
        $this->display();
    }

    /**
     * Send daily reminder mail.
     * 
     * @access public
     * @return void
     */
    public function remind()
    {
        $bugs = $tasks = $todos = $testTasks = array();
        if($this->config->report->dailyreminder->bug)      $bugs  = $this->report->getUserBugs();
        if($this->config->report->dailyreminder->task)     $tasks = $this->report->getUserTasks();
        if($this->config->report->dailyreminder->todo)     $todos = $this->report->getUserTodos();
        if($this->config->report->dailyreminder->testTask) $testTasks = $this->report->getUserTestTasks();
        
        $reminder = array();

        $users = array_unique(array_merge(array_keys($bugs), array_keys($tasks), array_keys($todos), array_keys($testTasks)));
        if(!empty($users)) foreach($users as $user) $reminder[$user] = new stdclass();

        if(!empty($bugs))  foreach($bugs as $user => $bug)   $reminder[$user]->bugs  = $bug;
        if(!empty($tasks)) foreach($tasks as $user => $task) $reminder[$user]->tasks = $task;
        if(!empty($todos)) foreach($todos as $user => $todo) $reminder[$user]->todos = $todo;
        if(!empty($testTasks)) foreach($testTasks as $user => $testTask) $reminder[$user]->testTasks = $testTask;

        $this->loadModel('mail');

        /* Check mail turnon.*/
        if(!$this->config->mail->turnon)
        {
            echo "You should turn on the Email feature first.\n";
            return false;
        }

        foreach($reminder as $user => $mail)
        {
            /* Reset $this->output. */
            $this->clear();

            $mailTitle   = $this->lang->report->mailTitle->begin;
            $mailTitle  .= isset($mail->bugs)  ? sprintf($this->lang->report->mailTitle->bug,  count($mail->bugs))  : '';
            $mailTitle  .= isset($mail->tasks) ? sprintf($this->lang->report->mailTitle->task, count($mail->tasks)) : '';
            $mailTitle  .= isset($mail->todos) ? sprintf($this->lang->report->mailTitle->todo, count($mail->todos)) : '';
            $mailTitle  .= isset($mail->testTasks) ? sprintf($this->lang->report->mailTitle->testTask, count($mail->testTasks)) : '';
            $mailTitle   = rtrim($mailTitle, ',');

            /* Get email content and title.*/
            $this->view->mail = $mail;
            $mailContent = $this->parse('report', 'dailyreminder');
            
            /* Send email.*/
            echo date('Y-m-d H:i:s') . " sending to $user, ";
            $this->mail->send($user, $mailTitle, $mailContent, '', true);
            if($this->mail->isError())
            {
                echo "fail: \n" ;
                a($this->mail->getError());
            }
            echo "ok\n";
        }
    }

    /**
     * Send daily reminder mail.
     *
     * @access public
     * @return void
     */
    public function sendBugDaily()
    {
        //$projects = $this->loadModel('project')->getPairs('noclosed');
        $products = $this->loadModel('product')->getPairs('noclosed');
        $assign = $this->report->getBugAssign();
        $users = $this->loadModel('user')->getByDepId(1);
        $href = common::getSysURL() . $this->createLink('report', 'bugDaily');
        $talkModel = $this->loadModel("talk");
        $pc_href = $href;
        $userBugs = array();
        $productBugs = array();

        foreach($assign as $userId => $value){
            if (!array_key_exists($userId, $users)) continue;
            $bugs = $value["bug"];
            $count = 0;
            foreach($bugs as $name => $data){
                if(!in_array($name, $products)) continue;
                $projectBugCount = array_key_exists($name, $productBugs) ? $productBugs[$name] : 0;
                $projectBugCount += $data["count"];
                $productBugs[$name] = $projectBugCount;
                $count += $data["count"];
            }
            if($count > 0){
                $userBugs[$users[$userId]] = $count;
            }

        }
        arsort($userBugs);
        arsort($productBugs);
        /*$form = array();
        if(count($productBugs) > 0) {
            array_push($form, array(
                "key" => "◆",
                "value" => "产品BUG统计"
            ));
            foreach ($productBugs as $key => $value) {
                array_push($form, array(
                    "key" => "[$key] ",
                    "value" => $value
                ));
            }

        }

        if(count($userBugs) > 0){
            array_push($form, array(
                "key" => "◆",
                "value" => "用户BUG统计"
            ));
            foreach($userBugs as $key => $value){
                array_push($form, array(
                    "key" => "[$key] ",
                    "value" => $value
                ));
            }

        }

        if(count($form) == 0){
            return false;
        }


        $body =  array(
            "message_url" => $href,
            "pc_message_url" => $pc_href,
            "head" => array(
                "bgcolor" => "FFBBBBBB",
                "text" => "BUG报表"
            ),
            "body"=>array(
                "title" => date("Y/m/d") . ' - BUG报表',
                "form"=> $form,
                "author"=>"禅道"
            )
        );
        $talkModel->sendParty("-1", "oa" , $body);*/
        if(empty($productBugs) && empty($userBugs)){
            return false;
        }
        $title = date("Y/m/d") . " - BUG日报表";
        $text = "###  " . $title . "\n　\n";
        $text .= "#####  项目BUG统计 \n";
        foreach ($productBugs as $key => $value) {
            $text .= "[$key]    $value \n\n";
        }
        $text .="\n　\n";
        $text .="##### 用户BUG统计 \n";
        foreach($userBugs as $key => $value){
            $text .= "[$key]    $value \n\n";
        }

        $actionCard = array();
        $actionCard["title"] = $title;
        $actionCard["text"] = $text;
        $actionCard["singleTitle"] =  "查看详情";
        $actionCard["singleURL"] = $pc_href;

        $body = array("actionCard" => $actionCard, "msgtype"=>"actionCard");

        $talkModel->sendWebHook($body);
    }

    /**
     * Send daily reminder mail.
     *
     * @access public
     * @return void
     */
    public function sendTaskDaily()
    {
        $projects = $this->loadModel('project')->getPairs('noclosed');
        $assign = $this->report->getTaskDelayedAssign();
        $users = $this->loadModel('user')->getByDepId(1);
        $href = common::getSysURL() . $this->createLink('report', 'taskDelayedDaily');
        $talkModel = $this->loadModel("talk");
        $pc_href = $href;
        $userTasks = array();
        $productTasks = array();

        foreach($assign as $userId => $value){
            if (!array_key_exists($userId, $users)) continue;
            $tasks = $value["task"];
            $count = 0;
            foreach($tasks as $name => $data){
                if(!in_array($name, $projects)) continue;
                $projectTaskCount = array_key_exists($name, $productTasks) ? $productTasks[$name] : 0;
                $projectTaskCount += $data["count"];
                $productTasks[$name] = $projectTaskCount;
                $count += $data["count"];
            }
            if($count > 0){
                $userTasks[$users[$userId]] = $count;
            }

        }
        arsort($userTasks);
        arsort($productTasks);
        /*$form = array();
        if(count($productTasks) > 0) {
            array_push($form, array(
                "key" => "◆",
                "value" => "产品延期任务统计"
            ));
            foreach ($productTasks as $key => $value) {
                array_push($form, array(
                    "key" => "[$key] ",
                    "value" => $value
                ));
            }

        }

        if(count($userTasks) > 0){
            array_push($form, array(
                "key" => "◆",
                "value" => "用户延期任务统计"
            ));
            foreach($userTasks as $key => $value){
                array_push($form, array(
                    "key" => "[$key] ",
                    "value" => $value
                ));
            }

        }

        if(count($form) == 0){
            return false;
        }


        $body =  array(
            "message_url" => $href,
            "pc_message_url" => $pc_href,
            "head" => array(
                "bgcolor" => "FFBBBBBB",
                "text" => "延期任务报表"
            ),
            "body"=>array(
                "title" => date("Y/m/d") . ' - 延期任务报表',
                "form"=> $form,
                "author"=>"禅道"
            )
        );
        $talkModel->sendParty("-1", "oa" , $body);
        */

        if(empty($productTasks) && empty($userTasks)){
            return false;
        }
        $title = date("Y/m/d") . " - 延期任务日报表";
        $text = "###  " . $title . "\n　\n";
        $text .= "#####  项目延期任务统计 \n";
        foreach ($productTasks as $key => $value) {
            $text .= "[$key]    $value \n\n";
        }
        $text .="\n　\n";
        $text .="##### 用户延期任务统计 \n";
        foreach($userTasks as $key => $value){
            $text .= "[$key]    $value \n\n";
        }

        $actionCard = array();
        $actionCard["title"] = $title;
        $actionCard["text"] = $text;
        $actionCard["singleTitle"] =  "查看详情";
        $actionCard["singleURL"] = $pc_href;

        $body = array("actionCard" => $actionCard, "msgtype"=>"actionCard");

        $talkModel->sendWebHook($body);

    }


    /**
     * 发送服务器监控.
     *
     * @access public
     * @return void
     */
    public function sendServerMonitor()
    {
        //$projects = $this->loadModel('project')->getPairs('noclosed');
        $serverModel = $this->loadModel('server');
        $servers = $serverModel->findAll();
        $reports = array();
        foreach ($servers as $key => $server) {
            $res = $serverModel->get($server->url);
            $item = new stdclass();
            $item->name = $server->name;
            $item->status = empty($res) ? "异常" : "正常";
            array_push($reports, $item);
        }

        $talkModel = $this->loadModel("talk");


        $title = date("Y/m/d") . " - 服务器扫描结果";
        $text = "###  " . $title . "\n\n";
        foreach ($reports as $key => $item) {
            $text .= "**[$item->name]** 　　　$item->status \n\n";
        }

        $actionCard = array();
        $actionCard["title"] = $title;
        $actionCard["text"] = $text;
        $actionCard["singleTitle"] =  "";
        $actionCard["singleURL"] = "";

        $body = array("actionCard" => $actionCard, "msgtype"=>"actionCard");

        $talkModel->sendWebHook($body, 'https://oapi.dingtalk.com/robot/send?access_token=4c5ece4ba88e4af782eb9d8c4d26ac7316947abba720b9b64b2fa012292263a5');
    }
}
